'''
Created on Sep 8, 2012

@author: petrina
'''

from link_indicator import Link_indicator
from indiutils import Indiutils
import logging



class Variation_speeds(Link_indicator):
    '''
    Calculates the variation of travel speeds for every time interval (using aggregated fcd-data).
    
    Formula for calculating the indicator: 
        vs_i = 100 * std_i/ats_i  
            where:
                - vs_i  ... variation of speeds for the time interval i 
                - std_i  ... standard deviation for the time interval i
                - ats_i ...  average travel time for the time interval i
    
    The standard deviation comes from the timeseries.
    self.unit.__doc__ = 'percent (%)'
    '''
    

    def __init__(self, link):
        '''        
        @param link: Link-object (containing valid records and timeseries) 
        '''
        
        Link_indicator.__init__(self, link)
        self._name = 'Variation of Travel-Speeds'
        self._mr_name =  'var_speed'
        self._unit = '%'
        #self.unit.__doc__ = 'percent (%)'

        self._create_title(link.id, link.direction)
        
        logging.debug("Variation_speeds: created new Variation_speeds")
        
        
    #----------------------public methods of the class-------------------------

    def calculate(self):
        '''
        @return: variation of speeds for every time interval as list of Result_values
        '''
        
        logging.info("Variation_speeds: staring to calculate the variation of speeds")
        
        utils = Indiutils()
        std = utils.stddev_speed(self._link.timeseries)
        ats = utils.calc_average_of(self._link.records, "speed")
        self._values = []
        
        for i in range(self._intervals):
            vi = None if std[i] is None or ats[i] is None else 100 * std[i]/ats[i]
            self._values.append(vi)

        logging.debug("Variation_speeds: finished calculating the variation of speeds")

        return self._values


    